package org.chnxi.study.leetcode.questions25.ques8;

/**
 * 执行用时 :2 ms, 在所有 Java 提交中击败了99.56%的用户
 * 内存消耗 :40 MB, 在所有 Java 提交中击败了5.77%的用户
 */
public class Simple1 {

    public static void main(String[] args) {
        String str1 = "42"; // 42
        System.out.println("str1="+myAtoi(str1));

        String str2 = " -42"; //-42
        System.out.println("str2="+myAtoi(str2));

        String str3 = "4193 with words"; //4193
        System.out.println("str3="+myAtoi(str3));

        String str4 = "words and 987"; //0
        System.out.println("str4="+myAtoi(str4));

        String str5 = "-91283472332"; // Integer.MIN_VALUE
        System.out.println("str5="+myAtoi(str5));

        String str6 = "-+1"; // Integer.MIN_VALUE
        System.out.println("str6="+myAtoi(str6));

        System.out.println("MAX="+Integer.MAX_VALUE);
        System.out.println("MIN="+Integer.MIN_VALUE);
    }

    public static int myAtoi(String str) {
        //null或者空的判断
        if(str == null || (str = str.trim()).length() == 0){
            return 0;
        }

        char[] chars = str.toCharArray();
        int flag = 1; // 标记符号位
        //首字符不是-、+与数字
        if(chars[0] != '-' && chars[0] != '+' && (chars[0] < '0' || chars[0] > '9')){
            return 0;
        }

        //负数处理
        if(chars[0] == '-'){
            flag = -1;
        }

        long result = 0; //记录最终结果
        boolean out = false; //记录是否越界

        for (int i=0; i<chars.length;i++){
            //如果首位是符号位，跳过
            if(i ==0 && (chars[i] == '-' || chars[i] == '+')){
                continue;
            }

            //后续字符不是数字
            if(chars[i] < '0' || chars[i] > '9'){
                break;
            }

            //对数字位进行解析
            result = result*10 + (chars[i]-48);

            if(flag == 1 && result>Integer.MAX_VALUE){
                out = true;
            }else if(flag == -1 && result-1 > Integer.MAX_VALUE ){
                out = true;
            }
        }

        result = result * flag;

        if(flag == 1 && out){
            return Integer.MAX_VALUE;
        }else if(flag == 1){
            return (int)result;
        }else if(flag == -1 && out){
            return Integer.MIN_VALUE;
        }else{
            return (int)result;
        }
    }
}
